<template>
  <div class="question-bank-container">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <div class="header-left">
        <h1>题库管理</h1>
        <p>管理课程的考试题目</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showAddDialog = true">
          <el-icon><Plus /></el-icon>
          添加题目
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="课程">
          <el-select v-model="filterForm.courseId" placeholder="选择课程" clearable style="width: 200px">
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.title"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题型">
          <el-select v-model="filterForm.questionType" placeholder="选择题型" clearable style="width: 150px">
            <el-option label="单选题" value="SINGLE_CHOICE" />
            <el-option label="多选题" value="MULTIPLE_CHOICE" />
            <el-option label="判断题" value="TRUE_FALSE" />
            <el-option label="填空题" value="FILL_BLANK" />
            <el-option label="问答题" value="ESSAY" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="filterForm.difficulty" placeholder="选择难度" clearable style="width: 120px">
            <el-option label="简单" value="EASY" />
            <el-option label="中等" value="MEDIUM" />
            <el-option label="困难" value="HARD" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索题目内容"
            style="width: 200px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadQuestions">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 题目列表 -->
    <div class="questions-section">
      <el-table v-loading="loading" :data="questions" stripe>
        <el-table-column prop="title" label="题目标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="courseName" label="所属课程" width="150" />
        <el-table-column prop="questionType" label="题型" width="100">
          <template #default="{ row }">
            <el-tag :type="getQuestionTypeColor(row.questionType)">
              {{ getQuestionTypeText(row.questionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="80">
          <template #default="{ row }">
            <el-tag :type="getDifficultyColor(row.difficulty)" size="small">
              {{ getDifficultyText(row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="分值" width="80" />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewQuestion(row)">
              查看
            </el-button>
            <el-button type="warning" size="small" @click="editQuestion(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="deleteQuestion(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑题目对话框 -->
    <el-dialog
      v-model="showQuestionDialog"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="questionForm" :rules="questionRules" ref="questionFormRef" label-width="100px">
        <el-form-item label="所属课程" prop="courseId">
          <el-select v-model="questionForm.courseId" placeholder="选择课程" style="width: 100%">
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.title"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="题目标题" prop="title">
          <el-input v-model="questionForm.title" placeholder="请输入题目标题" />
        </el-form-item>
        
        <el-form-item label="题目内容" prop="content">
          <el-input
            v-model="questionForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入题目内容"
          />
        </el-form-item>
        
        <el-form-item label="题目类型" prop="questionType">
          <el-select v-model="questionForm.questionType" @change="onQuestionTypeChange" style="width: 200px">
            <el-option label="单选题" value="SINGLE_CHOICE" />
            <el-option label="多选题" value="MULTIPLE_CHOICE" />
            <el-option label="判断题" value="TRUE_FALSE" />
            <el-option label="填空题" value="FILL_BLANK" />
            <el-option label="问答题" value="ESSAY" />
          </el-select>
        </el-form-item>

        <!-- 选择题选项 -->
        <el-form-item 
          v-if="['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(questionForm.questionType)" 
          label="题目选项"
          prop="options"
        >
          <div class="options-container">
            <div v-for="(option, index) in questionForm.options" :key="index" class="option-item">
              <el-input
                v-model="option.content"
                :placeholder="`选项 ${String.fromCharCode(65 + index)}`"
                style="flex: 1; margin-right: 10px"
              />
              <el-button
                v-if="questionForm.options.length > 2"
                type="danger"
                size="small"
                @click="removeOption(index)"
              >
                删除
              </el-button>
            </div>
            <el-button
              v-if="questionForm.options.length < 6"
              type="primary"
              size="small"
              @click="addOption"
            >
              添加选项
            </el-button>
          </div>
        </el-form-item>

        <!-- 正确答案 -->
        <el-form-item label="正确答案" prop="correctAnswers">
          <!-- 单选题答案 -->
          <el-radio-group 
            v-if="questionForm.questionType === 'SINGLE_CHOICE'" 
            v-model="singleCorrectAnswer"
            @change="updateCorrectAnswers"
          >
            <el-radio
              v-for="(option, index) in questionForm.options"
              :key="index"
              :label="String.fromCharCode(65 + index)"
            >
              {{ String.fromCharCode(65 + index) }}
            </el-radio>
          </el-radio-group>
          
          <!-- 多选题答案 -->
          <el-checkbox-group 
            v-else-if="questionForm.questionType === 'MULTIPLE_CHOICE'" 
            v-model="multipleCorrectAnswers"
            @change="updateCorrectAnswers"
          >
            <el-checkbox
              v-for="(option, index) in questionForm.options"
              :key="index"
              :label="String.fromCharCode(65 + index)"
            >
              {{ String.fromCharCode(65 + index) }}
            </el-checkbox>
          </el-checkbox-group>
          
          <!-- 判断题答案 -->
          <el-radio-group 
            v-else-if="questionForm.questionType === 'TRUE_FALSE'" 
            v-model="trueFalseAnswer"
            @change="updateCorrectAnswers"
          >
            <el-radio label="true">正确</el-radio>
            <el-radio label="false">错误</el-radio>
          </el-radio-group>
          
          <!-- 填空题/问答题答案 -->
          <el-input
            v-else
            v-model="textAnswer"
            type="textarea"
            :rows="3"
            placeholder="请输入标准答案"
            @input="updateCorrectAnswers"
          />
        </el-form-item>

        <el-form-item label="难度" prop="difficulty">
          <el-select v-model="questionForm.difficulty" style="width: 150px">
            <el-option label="简单" value="EASY" />
            <el-option label="中等" value="MEDIUM" />
            <el-option label="困难" value="HARD" />
          </el-select>
        </el-form-item>

        <el-form-item label="分值" prop="points">
          <el-input-number
            v-model="questionForm.points"
            :min="1"
            :max="100"
            :step="0.5"
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="答案解析">
          <el-input
            v-model="questionForm.explanation"
            type="textarea"
            :rows="3"
            placeholder="请输入答案解析（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showQuestionDialog = false">取消</el-button>
        <el-button type="primary" @click="saveQuestion" :loading="saving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 查看题目对话框 -->
    <el-dialog v-model="showViewDialog" title="题目详情" width="700px">
      <div v-if="selectedQuestion" class="question-detail">
        <div class="detail-item">
          <label>题目标题：</label>
          <span>{{ selectedQuestion.title }}</span>
        </div>
        <div class="detail-item">
          <label>题目内容：</label>
          <div class="content">{{ selectedQuestion.content }}</div>
        </div>
        <div class="detail-item">
          <label>题目类型：</label>
          <el-tag :type="getQuestionTypeColor(selectedQuestion.questionType)">
            {{ getQuestionTypeText(selectedQuestion.questionType) }}
          </el-tag>
        </div>
        <div v-if="selectedQuestion.options" class="detail-item">
          <label>选项：</label>
          <div class="options">
            <div v-for="(option, index) in selectedQuestion.options" :key="index" class="option">
              {{ String.fromCharCode(65 + index) }}. {{ typeof option === 'string' ? option : option.content }}
            </div>
          </div>
        </div>
        <div class="detail-item">
          <label>正确答案：</label>
          <span class="answer">{{ formatCorrectAnswers(selectedQuestion.correctAnswers) }}</span>
        </div>
        <div v-if="selectedQuestion.explanation" class="detail-item">
          <label>答案解析：</label>
          <div class="explanation">{{ selectedQuestion.explanation }}</div>
        </div>
        <div class="detail-item">
          <label>难度：</label>
          <el-tag :type="getDifficultyColor(selectedQuestion.difficulty)" size="small">
            {{ getDifficultyText(selectedQuestion.difficulty) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <label>分值：</label>
          <span>{{ selectedQuestion.points }} 分</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { questionApi, examApi } from '@/api/exam'
import type { Question, QuestionRequest } from '@/api/exam'
import { courseApi, type Course } from '@/api/course'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const questions = ref<Question[]>([])
const courses = ref<Course[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const showQuestionDialog = ref(false)
const showAddDialog = ref(false)
const showViewDialog = ref(false)
const selectedQuestion = ref<Question>()
const questionFormRef = ref()

// 筛选表单
const filterForm = reactive({
  courseId: '',
  questionType: '',
  difficulty: '',
  keyword: ''
})

// 题目表单
const questionForm = reactive({
  id: undefined as number | undefined,
  courseId: 0,
  title: '',
  content: '',
  questionType: 'SINGLE_CHOICE' as 'SINGLE_CHOICE' | 'MULTIPLE_CHOICE' | 'TRUE_FALSE' | 'FILL_BLANK' | 'ESSAY',
  options: [
    { content: '' },
    { content: '' }
  ] as Array<{ content: string }>,
  correctAnswers: [] as string[],
  explanation: '',
  difficulty: 'MEDIUM' as 'EASY' | 'MEDIUM' | 'HARD',
  points: 5.0
})

// 答案相关状态
const singleCorrectAnswer = ref('')
const multipleCorrectAnswers = ref<string[]>([])
const trueFalseAnswer = ref('')
const textAnswer = ref('')

// 表单验证规则
const questionRules = {
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  title: [{ required: true, message: '请输入题目标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
  questionType: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
  difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
  points: [{ required: true, message: '请输入分值', trigger: 'blur' }]
}

// 计算属性
const dialogTitle = ref('添加题目')

// 工具函数
const getQuestionTypeText = (type: string) => {
  const typeMap = {
    SINGLE_CHOICE: '单选题',
    MULTIPLE_CHOICE: '多选题',
    TRUE_FALSE: '判断题',
    FILL_BLANK: '填空题',
    ESSAY: '问答题'
  }
  return typeMap[type as keyof typeof typeMap] || type
}

const getQuestionTypeColor = (type: string) => {
  const colorMap = {
    SINGLE_CHOICE: 'primary',
    MULTIPLE_CHOICE: 'success',
    TRUE_FALSE: 'warning',
    FILL_BLANK: 'info',
    ESSAY: 'danger'
  }
  return colorMap[type as keyof typeof colorMap] || ''
}

const getDifficultyText = (difficulty: string) => {
  const difficultyMap = {
    EASY: '简单',
    MEDIUM: '中等',
    HARD: '困难'
  }
  return difficultyMap[difficulty as keyof typeof difficultyMap] || difficulty
}

const getDifficultyColor = (difficulty: string) => {
  const colorMap = {
    EASY: 'success',
    MEDIUM: 'warning',
    HARD: 'danger'
  }
  return colorMap[difficulty as keyof typeof colorMap] || ''
}

const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

const formatCorrectAnswers = (answers: string[]) => {
  if (!answers || answers.length === 0) return '未设置'
  return answers.join(', ')
}

// 页面方法
const loadCourses = async () => {
  try {
    const res = await courseApi.getTeacherCourses({ page: 1, pageSize: 100 })
    courses.value = res.content || []
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  }
}

const loadQuestions = async () => {
  try {
    loading.value = true
    
    // 如果没有选择课程，获取第一个课程
    if (!filterForm.courseId && courses.value.length > 0) {
      filterForm.courseId = String(courses.value[0].id)
    }
    
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      courseId: filterForm.courseId ? Number(filterForm.courseId) : undefined,
      questionType: filterForm.questionType || undefined,
      difficulty: filterForm.difficulty || undefined,
      keyword: filterForm.keyword || undefined
    }
    
    console.log('题库查询参数:', params)
    const res = await questionApi.search(params)
    console.log('题库查询响应:', res)
    
    // 处理返回的数据，将JSON字符串解析为数组
    const processedQuestions = ((res as any).data?.content || (res as any).content || []).map((question: any) => {
      if (typeof question.options === 'string' && question.options) {
        try {
          question.options = JSON.parse(question.options)
        } catch (e) {
          question.options = []
        }
      }
      if (typeof question.correctAnswers === 'string' && question.correctAnswers) {
        try {
          question.correctAnswers = JSON.parse(question.correctAnswers)
        } catch (e) {
          question.correctAnswers = []
        }
      }
      return question
    })
    
    questions.value = processedQuestions
    total.value = (res as any).data?.totalElements || (res as any).totalElements || 0
  } catch (error) {
    console.error('获取题目列表失败:', error)
    ElMessage.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilter = () => {
  filterForm.courseId = ''
  filterForm.questionType = ''
  filterForm.difficulty = ''
  filterForm.keyword = ''
  loadQuestions()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  loadQuestions()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadQuestions()
}

// 题目操作
const viewQuestion = (question: Question) => {
  selectedQuestion.value = question
  showViewDialog.value = true
}

const editQuestion = (question: Question) => {
  // 填充表单数据
  Object.assign(questionForm, {
    id: question.id,
    courseId: question.courseId,
    title: question.title,
    content: question.content,
    questionType: question.questionType,
    options: question.options || [{ content: '' }, { content: '' }],
    correctAnswers: question.correctAnswers || [],
    explanation: question.explanation || '',
    difficulty: question.difficulty,
    points: question.points
  })
  
  // 设置答案状态
  if (question.questionType === 'SINGLE_CHOICE') {
    singleCorrectAnswer.value = question.correctAnswers?.[0] || ''
  } else if (question.questionType === 'MULTIPLE_CHOICE') {
    multipleCorrectAnswers.value = [...(question.correctAnswers || [])]
  } else if (question.questionType === 'TRUE_FALSE') {
    trueFalseAnswer.value = question.correctAnswers?.[0] || ''
  } else {
    textAnswer.value = question.correctAnswers?.[0] || ''
  }
  
  dialogTitle.value = '编辑题目'
  showQuestionDialog.value = true
}

const deleteQuestion = async (question: Question) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除题目"${question.title}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await questionApi.delete(question.id)
    ElMessage.success('删除成功')
    loadQuestions()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除题目失败:', error)
      ElMessage.error('删除题目失败')
    }
  }
}

// 选项操作
const addOption = () => {
  questionForm.options.push({ content: '' })
}

const removeOption = (index: number) => {
  questionForm.options.splice(index, 1)
  // 清理已选择的答案
  if (questionForm.questionType === 'SINGLE_CHOICE') {
    const removedOption = String.fromCharCode(65 + index)
    if (singleCorrectAnswer.value === removedOption) {
      singleCorrectAnswer.value = ''
    }
  } else if (questionForm.questionType === 'MULTIPLE_CHOICE') {
    const removedOption = String.fromCharCode(65 + index)
    const answerIndex = multipleCorrectAnswers.value.indexOf(removedOption)
    if (answerIndex > -1) {
      multipleCorrectAnswers.value.splice(answerIndex, 1)
    }
  }
  updateCorrectAnswers()
}

// 题型变化处理
const onQuestionTypeChange = () => {
  // 重置选项和答案
  if (['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(questionForm.questionType)) {
    if (questionForm.options.length < 2) {
      questionForm.options = [{ content: '' }, { content: '' }]
    }
  } else {
    questionForm.options = []
  }
  
  singleCorrectAnswer.value = ''
  multipleCorrectAnswers.value = []
  trueFalseAnswer.value = ''
  textAnswer.value = ''
  questionForm.correctAnswers = []
}

// 答案更新
const updateCorrectAnswers = () => {
  if (questionForm.questionType === 'SINGLE_CHOICE') {
    questionForm.correctAnswers = singleCorrectAnswer.value ? [singleCorrectAnswer.value] : []
  } else if (questionForm.questionType === 'MULTIPLE_CHOICE') {
    questionForm.correctAnswers = [...multipleCorrectAnswers.value]
  } else if (questionForm.questionType === 'TRUE_FALSE') {
    questionForm.correctAnswers = trueFalseAnswer.value ? [trueFalseAnswer.value] : []
  } else {
    questionForm.correctAnswers = textAnswer.value ? [textAnswer.value] : []
  }
}

// 保存题目
const saveQuestion = async () => {
  try {
    await questionFormRef.value.validate()
    
    // 验证选择题选项
    if (['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(questionForm.questionType)) {
      const validOptions = questionForm.options.filter(opt => opt.content.trim())
      if (validOptions.length < 2) {
        ElMessage.error('选择题至少需要2个选项')
        return
      }
      questionForm.options = validOptions
    }
    
    // 验证答案
    if (!questionForm.correctAnswers || questionForm.correctAnswers.length === 0) {
      ElMessage.error('请设置正确答案')
      return
    }
    
    saving.value = true
    
    // 准备提交数据，将数组格式转换为JSON字符串
    // 注意：编辑题目时不要在请求体中包含id字段，id应该在URL路径中
    const submitData: any = {
      courseId: Number(questionForm.courseId),
      title: questionForm.title,
      content: questionForm.content,
      questionType: questionForm.questionType,
      points: Number(questionForm.points),
      explanation: questionForm.explanation,
      difficulty: questionForm.difficulty,
      options: questionForm.options && questionForm.options.length > 0 
        ? JSON.stringify(questionForm.options) 
        : undefined,
      correctAnswers: JSON.stringify(questionForm.correctAnswers)
    }
    
    // 不要在submitData中添加id字段，因为后端DTO不支持
    // ID通过URL路径传递：PUT /api/v1/exams/questions/{id}
    
    if (questionForm.id) {
      await questionApi.update(questionForm.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await questionApi.create(submitData)
      ElMessage.success('添加成功')
    }
    
    showQuestionDialog.value = false
    loadQuestions()
  } catch (error) {
    console.error('保存题目失败:', error)
    ElMessage.error('保存题目失败')
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetQuestionForm = () => {
  Object.assign(questionForm, {
    id: undefined,
    courseId: 0,
    title: '',
    content: '',
    questionType: 'SINGLE_CHOICE' as 'SINGLE_CHOICE' | 'MULTIPLE_CHOICE' | 'TRUE_FALSE' | 'FILL_BLANK' | 'ESSAY',
    options: [{ content: '' }, { content: '' }] as Array<{ content: string }>,
    correctAnswers: [] as string[],
    explanation: '',
    difficulty: 'MEDIUM' as 'EASY' | 'MEDIUM' | 'HARD',
    points: 5.0
  })
  
  singleCorrectAnswer.value = ''
  multipleCorrectAnswers.value = []
  trueFalseAnswer.value = ''
  textAnswer.value = ''
}

// 监听对话框
watch(() => showAddDialog.value, (newVal) => {
  if (newVal) {
    resetQuestionForm()
    dialogTitle.value = '添加题目'
    showQuestionDialog.value = true
    showAddDialog.value = false
  }
})

// 页面初始化
onMounted(() => {
  loadCourses()
  loadQuestions()
})
</script>

<style scoped>
.question-bank-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left h1 {
  margin: 0 0 5px 0;
  font-size: 24px;
  color: #333;
}

.header-left p {
  margin: 0;
  color: #666;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.questions-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.options-container {
  width: 100%;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.question-detail {
  padding: 10px 0;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item label {
  font-weight: bold;
  color: #333;
  display: inline-block;
  min-width: 80px;
}

.detail-item .content,
.detail-item .explanation {
  margin-top: 5px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  white-space: pre-wrap;
}

.detail-item .options {
  margin-top: 5px;
}

.detail-item .option {
  padding: 5px 10px;
  margin: 2px 0;
  background: #f8f9fa;
  border-radius: 4px;
}

.detail-item .answer {
  color: #409eff;
  font-weight: 600;
}
</style>
